<?php

class spAddToListFormComponents extends spAddToListBase
{
	public function __construct( $data=null )
	{
		parent::__construct( $data );
		parent::setClass( "spAddToListBase spAddToListFormComponents" );
	}
	
	// overrides base classes method
	protected function createInsertHtml( $param )
	{
		$data = parent::getData();
		
		// FIXME: remove wordpress code and find a way to create the path to the image
		$img = get_option('home').'/wp-content/plugins/gym/sigmaphp/html/extended/dragbar_gray.png';
		$i = new spImage(array("src"=>$img));
		$i->addAttr( "align", "top" );

		$divName = new spDiv(array(
			"class" => "componentDiv spPropertySheet"
		));
		
		$combo = new spCombobox(array(
			"list" => array(
				array("content"=>"combobox"),
				array("content"=>"date"),
				array("content"=>"listtext"),
				array("content"=>"radio"),
				array("content"=>"text"),
				array("content"=>"textarea")
			)
		));
		
		// this is the one that gets the property values
		$hiddenInput = new spInput(array(
			"type" => "hidden",
			"value" => '
				{
					"content_id" : "mytestid",
					"sections" : [
						{
							"title" : "my test section",
							"properties" : [
								{
									"type"	: "text",
									"title" : "mytext",
									"value" : "helloworld"
								}
							]
						}
					]
				}'
		));
		$divName->addChild( $hiddenInput );
		
		$table = new spTableExt;
		$table->addRowChilds( array(
			$i,
			$combo,
			$divName			
		));
		
		return $table;
	}	
	
	public function setElementDataString( $s )
	{
		parent::setElementDataString( $s );
		
		$insert_here = $this->find("insert_here");
		
		$obj = json_decode( $s, true );

		// support for old comma seperated format (remove this when not needed anymore)
		if ( !is_array($obj) )
		{
			$obj_new = array();
			
			$ar = explode( ",", $s );
			foreach ( $ar as $a )
			{
				$obj_new[] = array( "text"=>$a );
			}
			
			$obj = $obj_new;
		}

		if ( count($obj) )
		{
			foreach ( $obj as $o )
			{
				$insert_here->addChild( $this->createCloneableContainer( array( 
					"value"=>$o["text"] 
				)));
			}
		}
	}	
	
	public function updateFromRequest()
	{
		parent::updateFromRequest();
		
		// convience variables
		$data = parent::getData();
		$r = $_REQUEST;	
		
		$name = isset($data["name"])?$data["name"]:"";

		$ar = $r[$name];
		
		// remove the first element which is the clone value
		$ar = array_slice( $r[$name], 1 );
		
		$obj = array();
		foreach ( $ar as $o )
		{
			$obj[] = array( "text" => $o );
		}	

		$this->setElementDataString( json_encode( $obj ) );
	}
}

?>